<script setup>
import {ref,onMounted} from 'vue'
import axios from "axios";
import {ElMessage,ElMessageBox} from "element-plus";
import {useRouter} from "vue-router";
onMounted(()=>{
  getAllCouponList()
})
// 优惠券列表
const tableData = ref([])
const req = ref({
  pageNum:1,
  pageSize:3
})
const total = ref()
const getAllCouponList = () => {
  axios.post('api/coupon/couponList',req.value).then(
      res=>{
        tableData.value = res.data.data.list
        total.value = res.data.data.total
      }
  )
}

// 检查优惠券是否即将过期（一天内过期）
const isExpiringSoon = (expirationDate) => {
  if (!expirationDate) return false
  const now = new Date()
  const expDate = new Date(expirationDate)
  const timeDiff = expDate.getTime() - now.getTime()
  const daysDiff = timeDiff / (1000 * 3600 * 24)
  return daysDiff <= 1 && daysDiff > 0
}
const handleSizeChange = () => {
  req.value.pageNum = 1
  getAllCouponList()
}
const handleCurrentChange = () => {
  getAllCouponList()
}
//领取优惠券
const handleEdit = (row) => {
  let couponId = row.id;
  axios.get('api/coupon/getCoupon/'+couponId).then(
      res=>{
        if(res.data.code === 200){
          ElMessage.success("领取成功")
        }else {
          ElMessage.error(res.data.msg)
        }
      }
  )
}
//删除优惠券
const deleted = (row) => {
  ElMessageBox.confirm("确认要删除吗?").then(res=>{
    let couponId = row.id;
    axios.get('api/coupon/delCoupon/'+couponId).then(
        res=>{
          if(res.data.code === 200){
            ElMessage.success("删除成功")
            getAllCouponList()
          }else {
            ElMessage.error(res.data.msg)
          }
        }
    )
  })
}
//添加优惠券
const addCouponFields = ref({})
const dialogFormVisible= ref(false)
const addCoupon = () => {
  dialogFormVisible.value = true
}

const add = () => {
  axios.post('api/coupon/addCoupon',addCouponFields.value).then(
      res=>{
        if(res.data.code === 200){
          ElMessage.success("添加成功")
          dialogFormVisible.value = false
          getAllCouponList()
        }else {
          ElMessage.error(res.data.msg)
        }
      }
  )
}

//两个动态下拉框
const couponTypeList = ref([])
const couponCategoryList = ref([])
axios.post('api/coupon/selCouponTypeList').then(
    res=>{
      if(res.data.code === 200){
        couponTypeList.value = res.data.data
      }else {
        ElMessage.error(res.data.msg)
      }
    }
)


axios.post('api/coupon/selCouponCategoryList').then(
    res=>{
      if(res.data.code === 200){
        couponCategoryList.value = res.data.data
      }else {
        ElMessage.error(res.data.msg)
      }
    }
)
// 我的优惠券
const ownDialogFormVisible = ref(false)
const ownCoupon = () => {
  ownDialogFormVisible.value = true
}
const ownCouponList = ref([])
const req2 = ref({
  pageNum:1,
  pageSize:3
})
const total2 = ref()
axios.post('api/coupon/ownCouponList',req2.value).then(
    res=>{
      if(res.data.code === 200){
        ownCouponList.value = res.data.data.list
        total2.value = res.data.data.total
      }else {
        ElMessage.error(res.data.msg)
      }
    }
)
</script>

<template>
<!--  添加优惠券-->
  <el-button @click="addCoupon">添加优惠券</el-button>
  <el-button @click="ownCoupon">我的优惠券</el-button>
<!--  列表-->
  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="id" label="序号" width="180" />
    <el-table-column prop="couponName" label="优惠券名称" width="180" />
    <el-table-column prop="dictCouponType" label="优惠券类型" width="180" />
    <el-table-column prop="dictApplicableCategory" label="适用分类" width="180" />
    <el-table-column prop="maximumLimit" label="满额限制" width="180" />
    <el-table-column prop="discountAmount" label="折扣金额" width="180" />
    <el-table-column prop="discountRate" label="折扣比例" width="180" />
    <el-table-column prop="validDays" label="有效天数" width="180" />
    <el-table-column prop="availableQuantity" label="可用数量" width="180" />
    <el-table-column prop="alreadyClaimedNum" label="已领取数量" width="180" />
    <el-table-column prop="alreadyUseNum" label="已使用数量" width="180" />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)">
          领取
        </el-button>
        <el-button
            size="small"
            type="danger"
            @click="deleted(scope.row)"
        >
          删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
<!--  分页-->
  <el-pagination
      v-model:current-page="req.pageNum"
      v-model:page-size="req.pageSize"
      :page-sizes="[3, 5, 10, 12]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
<!--  弹框-->
  <el-dialog v-model="dialogFormVisible" title="优惠券添加" width="500">
    <el-form :model="addCouponFields">
      <el-form-item label="优惠券名称">
        <el-input v-model="addCouponFields.couponName" />
      </el-form-item>
      <el-form-item label="优惠券类型">
        <el-select v-model="addCouponFields.couponType" placeholder="Select" style="width: 240px">
          <el-option
              v-for="item in couponTypeList"
              :key="item.dictValue"
              :label="item.dictName"
              :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="适用分类">
        <el-select v-model="addCouponFields.applicableCategory" placeholder="Select" style="width: 240px">
          <el-option
              v-for="item in couponCategoryList"
              :key="item.dictValue"
              :label="item.dictName"
              :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="满额限制">
        <el-input v-model="addCouponFields.maximumLimit" />
      </el-form-item>
      <el-form-item label="折扣金额">
        <el-input v-model="addCouponFields.discountAmount" />
      </el-form-item>
      <el-form-item label="折扣比例">
        <el-input v-model="addCouponFields.discountRate" />
      </el-form-item>
      <el-form-item label="有效天数">
        <el-input v-model="addCouponFields.validDays" />
      </el-form-item>
      <el-form-item label="可用数量">
        <el-input v-model="addCouponFields.availableQuantity" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false;addCouponFields.value = {}">取消</el-button>
        <el-button type="primary" @click="add">
          添加
        </el-button>
      </div>
    </template>
  </el-dialog>





<!--  我的优惠券-->
  <!--  弹框-->
  <el-dialog v-model="ownDialogFormVisible" title="我的优惠券" width="500">
    <el-table :data="ownCouponList" style="width: 100%;height: 80%">
      <el-table-column prop="id" label="序号" width="180" />
      <el-table-column prop="couponName" label="优惠券名称" width="180">
        <template #default="scope">
          <span :class="{ 'used-coupon': scope.row.status == 1 }">
            {{ scope.row.couponName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="getTime" label="领取时间" width="180">
        <template #default="scope">
          <span :class="{ 'used-coupon': scope.row.status == 1 }">
            {{ scope.row.getTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="dictCouponType" label="使用品类" width="180">
        <template #default="scope">
          <span :class="{ 'used-coupon': scope.row.status == 1 }">
            {{ scope.row.dictCouponType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="expirationDate" label="过期时间" width="180">
        <template #default="scope">
          <span :class="{ 
            'used-coupon': scope.row.status == 1,
            'expiring-soon': scope.row.status == 2 && isExpiringSoon(scope.row.expirationDate)
          }">
            {{ scope.row.expirationDate }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="使用状态" width="180" >
      <template #default="scope">
        <el-tag 
          v-if="scope.row.status == 1" 
          :class="{ 'used-coupon': scope.row.status == 1 }"
        >已使用</el-tag>
        <el-tag 
          v-if="scope.row.status == 2" 
          :class="{ 'expiring-soon': isExpiringSoon(scope.row.expirationDate) }"
        >未使用</el-tag>
        <el-tag v-if="scope.row.status == 3">已过期</el-tag>
      </template>
      </el-table-column>
    </el-table>

    <!--  分页-->
    <el-pagination
        v-model:current-page="req2.pageNum"
        v-model:page-size="req2.pageSize"
        :page-sizes="[3, 5, 10, 12]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total2"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />
  </el-dialog>
</template>

<style scoped>
.used-coupon {
  color: #999;
  opacity: 0.6;
}

.expiring-soon {
  color: red;
  font-weight: bold;
}
</style>
